import React, { Component } from 'react';
import { DatePicker, Modal, Checkbox, Select, Form, Input, InputNumber, Tag } from 'antd'
import moment from 'moment'
import './style.less'
export default class Calendar extends Component {
  constructor() {
    super()
    this.formRef = React.createRef()
    this.state = {
      visible: false,
      weekDayNum: 7,
      today_date: moment(new Date()).format("yyyy-MM"),
      daysOfMonth: [],
      current_date: moment(new Date()).format("yyyy-MM"),
      current_day: moment(new Date()).format("DD"),
      checkDay: '',
      // 日历头部
      calendar_head: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      weekday: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    }
  }
  componentDidMount() {
    this.setState({
      daysOfMonth: this.getCalendarAllDays(this.current_date)
    }, () => {
      console.log(this.state.daysOfMonth, 'daysOfMonth')
    })
  }
  // 获取当前月份日历所有日期
  createMonthDay = (stime, etime) => {
    //初始化日期列表，数组
    let diffdate = new Array();
    let i = 0;
    //开始日期小于等于结束日期,并循环
    while (stime <= etime) {
      diffdate[i] = stime;

      //获取开始日期时间戳
      let stime_ts = new Date(stime).getTime();
      // console.log("当前日期：" + stime + "当前时间戳：" + stime_ts);

      //增加一天时间戳后的日期
      let next_date = stime_ts + 24 * 60 * 60 * 1000;

      //拼接年月日，这里的月份会返回（0-11），所以要+1
      let next_dates_y = new Date(next_date).getFullYear() + "-";
      let next_dates_m =
        new Date(next_date).getMonth() + 1 < 10
          ? "0" + (new Date(next_date).getMonth() + 1) + "-"
          : new Date(next_date).getMonth() + 1 + "-";
      let next_dates_d =
        new Date(next_date).getDate() < 10
          ? "0" + new Date(next_date).getDate()
          : new Date(next_date).getDate();

      stime = next_dates_y + next_dates_m + next_dates_d;

      //增加数组key
      i++;
    }
    return diffdate;
  };
  getWeekDays = (date) => {
    let oneDayTime = 1000 * 60 * 60 * 24;
    let today = new Date(date);
    // 若那一天是周末时，则强制赋值为7
    let todayDay = today.getDay() || 7;
    let startDate = new Date(today.getTime() - oneDayTime * (todayDay - 1));
    let dateList = new Array();
    for (let i = 0; i < 7; i++) {
      let temp = new Date(startDate.getTime() + i * oneDayTime);
      let year = temp.getFullYear();
      let month =
        temp.getMonth() + 1 < 10
          ? "0" + (temp.getMonth() + 1)
          : temp.getMonth() + 1;
      let day = temp.getDate() < 10 ? "0" + temp.getDate() : temp.getDate();
      dateList[i] = `${year}-${month}-${day}`;
    }
    return dateList;
  };
  getFirstAndLastDay = (date) => {
    let now = date ? new Date(date) : new Date(); //当前日期
    let nowMonth = now.getMonth(); //当前月
    let nowYear = now.getFullYear(); //当前年
    //本月的开始时间
    let monthStartDate = new Date(nowYear, nowMonth, 1);
    //本月的结束时间
    let monthEndDate = new Date(nowYear, nowMonth + 1, 0);
    let timeStar = moment(Date.parse(monthStartDate)).format("yyyy-MM-DD"); //s
    let timeEnd = moment(Date.parse(monthEndDate)).format("yyyy-MM-DD"); //s
    return [timeStar, timeEnd];
  };
  getNextDate = (date, day) => {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + day);
    let y = dd.getFullYear();
    let m =
      dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
    let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return y + "-" + m + "-" + d;
  };
  getNextWeek = (date, len) => {
    let times = [];
    for (let i = 0; i <= len; i++) {
      times.push(moment(date).add(i, "d").format("yyyy-MM-DD"));
    }
    return times;
  };
  getCalendarAllDays = (date) => {
    let time = [];
    let startAndEnd = this.getFirstAndLastDay(date);
    let firstWeek = this.getWeekDays(startAndEnd[0]),
      lastWeek = this.getWeekDays(startAndEnd[1]),
      currentMonthDays = this.createMonthDay(startAndEnd[0], startAndEnd[1]);

    firstWeek.unshift(this.getNextDate(firstWeek[0], -1));
    // 如果一号是周日
    if (new Date(startAndEnd[0]).getDay() == 0) {
      time = Array.from(new Set([...currentMonthDays, ...lastWeek]));
    } else {
      time = Array.from(
        new Set([...firstWeek, ...currentMonthDays, ...lastWeek])
      );
    }
    let nextWeeks = [];
    if (time.length < 42) {
      nextWeeks = this.getNextWeek(time[time.length - 1], 42 - time.length);
      time = Array.from(new Set([...time, ...nextWeeks]));
    } else {
      time = time.splice(0, 42);
    }
    return time;
  };

  getNextMonth = (date, addMonths) => {
    let dd = new Date(date);
    let m = dd.getMonth() + 1;
    let y =
      dd.getMonth() + 1 + addMonths > 12
        ? dd.getFullYear() + 1
        : dd.getFullYear();
    if (m + addMonths == 0) {
      y = y - 1;
      m = 12;
    } else {
      if (m + addMonths > 12) {
        m = "01";
      } else {
        m = m + 1 < 10 ? "0" + (m + addMonths) : m + addMonths;
      }
    }
    return y + "-" + m;
  };

  prevMonth = () => {
    const { current_date } = this.state
    let date = moment(this.getNextMonth(current_date, -1)).format("yyyy-MM");
    this.setState({
      current_date: date,
      daysOfMonth: this.getCalendarAllDays(current_date)
    })
  };
  nextMonth = () => {
    const { current_date } = this.state
    let date = moment(this.getNextMonth(current_date, 1)).format("yyyy-MM");
    this.setState({
      current_date: date,
      daysOfMonth: this.getCalendarAllDays(current_date)
    })
  };
  check = (time) => {
    const { today_date } = this.state
    let other =
      moment(time).format("MM") !== today_date.split("-")[1];
    let day = moment(time).format("DD");
    if (!other) {
      this.setState({
        checkDay: day,
        visible: true,

      })

    }
  };
  getMark = (time) => {
    const { current_day } = this.state

    let date = moment(time).format("DD");
    if (date > current_day) {
      // // 判断是否存在排班
      // //console.log(props.hasShiftDateStr, "peops.hasShiftDateStr", time);
      // if (props.hasShiftDateStr?.includes(time)) {
      //     return "background:#ffb321;box-shadow: 0px 0px 11px 1px rgba(255, 179, 33, 0.6);";
      // } else {
      //     return "display:none";
      // }
    } else if (date < current_day) {
      return "background:#2A70E9;box-shadow: 0px 0px 11px 1px rgba(42, 112, 233, 0.6);";
    } else {
      return "background:#00ff00;box-shadow: 0px 0px 11px 1px rgba(0, 255, 0, 0.6);";
    }
  };
  getTodayBc = (time) => {
    const { current_day } = this.state
    let date = moment(time).format("DD");

    if (date == current_day) {
      return "background:#011956";
    }
  };

  handleClick = (type) => {

  };
  onChange = (date, dateString) => {
    this.setState({
      current_date: dateString,
      today_date: dateString,
      daysOfMonth: this.getCalendarAllDays(dateString)
    }, () => {
      console.log(this.state.daysOfMonth, 'daysOfMonth')
    })
  }
  onFinish = (values) => {
    console.log('Success:', values);
  };
  onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  ok = () => {
    this.formRef.current.validateFields().then(values => {
      console.log(values, 'sssss')
    })
  }
  cancel = () => {
    setTimeout(() => {
      this.formRef.current.resetFields();
    }, 1000)
    this.setState({
      visible: false
    })
  }
  chooseRepeatDate(item, index) {
    const values = this.formRef.current.getFieldsValue()
    let repeatDate = values.repeatDate
    const has = repeatDate.indexOf(index)
    has > -1 ? repeatDate.splice(has, 1) : repeatDate.push(index)
    this.formRef.current.setFieldsValue({
      repeatDate
    })
  }
  render() {
    const { visible, weekday, today_date, current_date, checkDay, current_day, calendar_head, daysOfMonth, weekDayNum } = this.state
    return (
      <div className="p-layout-box calendarBox">
        {/* <GoBack history={this.props.history} style={{ margin: 20 }} title="价格日历" /> */}
        <div className='utils'>
          {/* <div className='currentRoomType'>自营品牌猫咪VIP房间</div> */}
          <DatePicker defaultValue={moment(current_date)} onChange={(date, dateString) => this.onChange(date, dateString)} picker="month" />
        </div>
        <div className="calendar">
          <div className="head">

            {
              calendar_head.map((item, index) => <div key={index + 'head'} className="col">{item}</div>)
            }

          </div>
          <div className="body">
            {
              Array.from(new Array(Math.ceil(daysOfMonth.length / 7)).keys()).map((week, week_index) => {
                return (
                  <div className="row" key={'week' + week_index}>
                    {
                      Array.from(new Array(weekDayNum).keys()).map((day, day_index) => {
                        return (
                          <div
                            key={'day' + day_index}
                            // style={this.getTodayBc(daysOfMonth[week_index * weekDayNum + day_index])}
                            className={
                              ['col',
                                moment(daysOfMonth[week_index * weekDayNum + day_index]).format('MM') !==
                                  current_date.split('-')[1] ||
                                  moment(daysOfMonth[week_index * weekDayNum + day_index]).format(
                                    'yyyy'
                                  ) !== today_date.split('-')[0] ||
                                  moment(today_date).format('MM') !== current_date.split('-')[1] ? 'otherMonth' : '',

                                checkDay ==
                                  moment(daysOfMonth[week_index * weekDayNum + day_index]).format('DD') ? "check" : ''
                              ].join(' ')
                            }
                            onClick={() => this.check(daysOfMonth[week_index * weekDayNum + day_index])}
                          >
                            <div className='riqi' key={'riqi' + week_index}>
                              {moment(daysOfMonth[week_index * weekDayNum + day_index]).format("DD")}
                            </div>
                          </div>
                        )
                      })
                    }
                  </div>
                )
              })
            }
          </div>
        </div >
        <Modal
          title={`修改价格 (${current_date}-${checkDay})`}
          visible={visible}
          onOk={this.ok}
          onCancel={this.cancel}
          okText="确认"
          cancelText="取消"
        >
          <Form
            name="basic"
            labelCol={{
              span: 4,
            }}
            colon={false}
            wrapperCol={{
              span: 16,
            }}
            ref={this.formRef}
            initialValues={{
              repeatDate: [1, 2, 3, 4, 5, 6, 7],
            }}

            autoComplete="off"
          >
            <Form.Item
              label="价格"
              name="price"
              rules={[
                {
                  required: true,
                  message: '请输入价格',
                },
              ]}
            >
              <InputNumber min={0} precision={2} />
            </Form.Item>
            <Form.Item
              label="重复"
              name="repeatType"

            >
              <Select
                defaultValue="today"
                options={[
                  {
                    value: 'today',
                    label: '仅当天',
                  },
                  {
                    value: 'everyWeek',
                    label: '每周',
                  }
                ]} />
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.repeatType !== currentValues.repeatType}
            >
              {
                ({ getFieldValue }) =>
                  getFieldValue('repeatType') === 'everyWeek' ?
                    <>
                      <Form.Item
                        label=" "
                        name="repeatDate"
                      >
                        <div className='repeatDates'>
                          {weekday.map((item, index) => <Tag key={index} color={getFieldValue('repeatDate') && getFieldValue('repeatDate').includes(index + 1) ? 'orange' : 'default'} style={{ marginRight: 0, cursor: 'pointer', padding: "4px 8px" }} onClick={() => this.chooseRepeatDate(item, index + 1)}>{item}</Tag>)}
                        </div>
                      </Form.Item>
                    </> : null
              }
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.repeatType !== currentValues.repeatType}
            >
              {
                ({ getFieldValue }) =>
                  getFieldValue('repeatType') === 'everyWeek' ?
                    <>
                      <Form.Item
                        label="结束重复"
                        name="overRepeatType"
                      >
                        <Select
                          defaultValue="never"
                          options={[

                            {
                              value: 'never',
                              label: '永不',
                            },
                            {
                              value: 'custom',
                              label: '日历选择',
                            }
                          ]} />
                      </Form.Item>
                    </> : null
              }
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.overRepeatType !== currentValues.overRepeatType}
            >
              {
                ({ getFieldValue }) =>
                  getFieldValue('overRepeatType') === 'custom' ?
                    <>
                      <Form.Item
                        label="结束时间"
                        name="overRepeatDate"
                        rules={[
                          {
                            required: true,
                            message: '请选择结束时间',
                          },
                        ]}
                      >
                        <DatePicker format={'YYYY-MM-DD'} />
                      </Form.Item>
                    </> : null
              }
            </Form.Item>

          </Form>
        </Modal>
      </div >
    );
  }
}
